package com.qiaoba.poi.excel.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.poi.excel.entity.ExcelSetting;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * Excel 工具类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/25 0025 上午 9:15
 */
public class ExcelUtil {

    /**
     * 默认导出
     *
     * @param list      数据
     * @param pojoClass java类
     * @param fileName  文件名
     * @param response  response
     */
    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        defaultExport(list, pojoClass, fileName, new ExportParams(fileName, fileName, ExcelType.XSSF), response);
    }

    /**
     * 自定义导出
     *
     * @param list     数据
     * @param entities 字段设置
     * @param fileName 文件名
     * @param response response
     */
    public static void exportExcel(List<?> list, List<ExcelExportEntity> entities, String fileName, HttpServletResponse response) {
        exportBySettings(list, entities, fileName, new ExportParams(fileName, fileName, ExcelType.XSSF), response);
    }

    private static void exportBySettings(List<?> list, List<ExcelExportEntity> entities, String fileName, ExportParams exportParams, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entities, list);
        downLoadExcel(fileName, response, workbook);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
            IOUtils.closeQuietly(workbook);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
        return importExcel(file.getInputStream(), 1, 1, pojoClass);
    }

    private static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
        if (inputStream == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        params.setSaveUrl("/excel/");
        try {
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new IOException("excel文件不能为空");
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        } finally {
            IoUtil.close(inputStream);
        }
    }

    public static List<ExcelExportEntity> createExcelEntry(List<ExcelSetting> settings) {
        List<ExcelExportEntity> entities = new ArrayList<>();
        for (ExcelSetting setting : settings) {
            // 去除隐藏
            if (!ExcelSetting.EXCEL_FIELD_SHOW_FLAG.equals(setting.getShow())) {
                continue;
            }
            ExcelExportEntity entity = new ExcelExportEntity(setting.getFieldName(), setting.getFieldId());
            entity.setWidth(Double.valueOf(setting.getWidth()));
            String replace = setting.getReplace();
            if (StrUtil.isNotBlank(replace) && replace.contains(",")) {
                entity.setReplace(replace.split(","));
            }
            entity.setFormat(setting.getDateFormat());
            entity.setOrderNum(setting.getSort());
            entities.add(entity);
        }
        return entities;
    }

}
